<template>
  <ContentWrap v-hasRole="['shop_admin']">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="功能开关" prop="enabled">
        <div class="flex flex-col">
          <el-switch
            v-model="formData.enabled"
            :active-value="true"
            :inactive-value="false"
            active-text="开启"
            inactive-text="关闭"
            inline-prompt
          />
          <el-text v-if="formData.enabled" type="info">
            功能关闭后扫码结果页面将不会弹出新客首单优惠窗口。
          </el-text>
          <el-text v-else type="info">功能开启后扫码结果页面将会弹出新客首单优惠窗口。</el-text>
        </div>
      </el-form-item>
      <el-form-item label="原价金额" prop="originPrice">
        <div class="flex flex-col">
          <el-input-number
            v-model="computedOriginPrice"
            :min="0"
            :step="1"
            :precision="2"
            placeholder="请输入原价金额"
            class="!w-240px"
          >
            <template #suffix>元</template>
          </el-input-number>
          <el-text type="info">若用户已经在店铺消费过，则将不会弹出新客首单优惠窗口。</el-text>
        </div>
      </el-form-item>
      <el-form-item label="优惠金额" prop="price">
        <div class="flex flex-col">
          <el-input-number
            v-model="computedPrice"
            :min="0"
            :step="1"
            :precision="2"
            placeholder="请输入优惠金额"
            class="!w-240px"
          >
            <template #suffix>元</template>
          </el-input-number>
          <el-text type="info">若用户还未在店铺消费过，则将会弹出新客首单优惠窗口。</el-text>
        </div>
      </el-form-item>
      <el-form-item label="奖励类型" prop="rewardType">
        <el-radio-group v-model="formData.rewardType">
          <el-radio v-for="item in rewardTypeOptions" :key="item.value" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="formData.rewardType === 1" label="红包金额" prop="redPacketAmount">
        <div class="flex flex-col">
          <el-input-number
            v-model="computedRedPacketAmount"
            :min="0"
            :step="1"
            :precision="2"
            placeholder="请输入红包金额"
            class="!w-240px"
          >
            <template #suffix>元</template>
          </el-input-number>
          <el-text type="info">新客首单优惠支付成功后，获得指定的红包金额</el-text>
        </div>
      </el-form-item>
      <el-form-item v-if="formData.rewardType === 2" label="引流赠品" prop="giftActivityIds">
        <div class="flex flex-col">
          <el-button type="success" plain @click="openGiftActivitySelect()">选择引流赠品</el-button>
          <div
            v-if="giftActivities && giftActivities.length > 0"
            class="flex items-center flex-wrap py-10px"
          >
            <b class="text-gray">已选赠品：</b>
            <el-tag v-for="item in giftActivities" :key="item.id">{{ item.name }}</el-tag>
          </div>
          <div
            v-else-if="formData.giftActivityNames && formData.giftActivityNames.length > 0"
            class="flex items-center flex-wrap py-10px"
          >
            <b class="text-gray">已选赠品：</b>
            <el-tag v-for="item in formData.giftActivityNames" :key="item">{{ item }}</el-tag>
          </div>
          <el-text type="info">新客首单优惠支付成功后，获得指定的引流赠品</el-text>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="formLoading">保 存</el-button>
      </el-form-item>
    </el-form>
    <GiftSelect ref="giftSelectFormRef" @change="handleGiftSelect" />
  </ContentWrap>
  <ContentWrap v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']">
    <div class="mt-[5px]">
      <el-table :data="tableData.list" size="large" v-loading="tableData.loading">
        <template #empty>
          <span>{{ !tableData.loading ? '没有相关数据' : '' }}</span>
        </template>
        <el-table-column label="所属店铺" min-width="100">
          <template #default="{ row }">
            <div>{{ row.shop?.name || row.shopId }}</div>
          </template>
        </el-table-column>
        <el-table-column label="原价金额">
          <template #default="{ row }">{{ fenToYuan(row.originPrice) }}元</template>
        </el-table-column>
        <el-table-column label="优惠金额">
          <template #default="{ row }">{{ fenToYuan(row.price) }}元</template>
        </el-table-column>
        <el-table-column label="奖励类型" min-width="120">
          <template #default="{ row }">
            <div v-if="row.rewardType === 0">无奖励</div>
            <div v-else-if="row.rewardType === 1">
              红包 {{ fenToYuan(row.redPacketAmount) }}元
            </div>
            <div v-else-if="row.rewardType === 2">
              赠品
              {{
                row.giftActivityNames && row.giftActivityNames.length > 0
                  ? row.giftActivityNames.join('、')
                  : '未知'
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          min-width="170"
        />
      </el-table>
      <Pagination
        v-model:limit="tableData.searchParam.pageSize"
        v-model:page="tableData.searchParam.pageNo"
        :total="tableData.total"
        @pagination="loadTableData"
      />
    </div>
  </ContentWrap>
</template>

<!--suppress HtmlUnknownAttribute -->
<script lang="ts" setup name="NewCustomerConfigList">
import * as NewCustomerConfigApi from '@/api/promotion/newcustomer/NewCustomerConfigApi'
import { dateFormatter } from '@/utils/formatTime'
import { fenToYuan, yuanToFen } from '@/utils'
import { checkRole } from '@/utils/permission'
import GiftSelect from '@/views/mall/promotion/gift/GiftSelect.vue'

const formLoading = ref(false)
const formData = ref<any>({
  id: undefined,
  enabled: true,
  originPrice: 0,
  price: 0,
  rewardType: 0,
  redPacketAmount: 0,
  giftActivityIds: [],
  giftActivityNames: []
})
const formRules = reactive({
  enabled: [{ required: true, message: '功能开关不能为空', trigger: 'blur' }],
  originPrice: [{ required: true, message: '原价金额不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '优惠金额不能为空', trigger: 'blur' }],
  rewardType: [{ required: true, message: '奖励类型不能为空', trigger: 'change' }],
  redPacketAmount: [
    {
      required: true,
      message: '红包金额不能为空',
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {
        if (formData.value.rewardType === 1 && (!value || value <= 0)) {
          callback(new Error('红包金额必须大于0'))
        } else {
          callback()
        }
      }
    }
  ],
  giftActivityIds: [
    {
      required: true,
      message: '请选择引流赠品',
      trigger: 'change',
      validator: (rule: any, value: any, callback: any) => {
        if (formData.value.rewardType === 2 && (!value || !value.length)) {
          callback(new Error('请选择引流赠品'))
        } else {
          callback()
        }
      }
    }
  ]
})
const formRef = ref()

const rewardTypeOptions = [
  { label: '无奖励', value: 0 },
  { label: '送专属红包', value: 1 },
  { label: '送引流赠品', value: 2 }
]

const giftSelectFormRef = ref()
const giftActivities = ref<any>([])
const openGiftActivitySelect = () => {
  giftSelectFormRef.value?.open()
}
const handleGiftSelect = async (e: any[]) => {
  console.debug(JSON.stringify(e))
  if (!e?.length) {
    message.error('请选择引流赠品')
    return
  }
  giftActivities.value = e
  formData.value.giftActivityIds = e.map((item) => item.id)
  formData.value.giftActivityNames = e.map((item) => item.name)
  await formRef.value.validate()
}

const submitForm = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      // 根据奖励类型清理不需要的字段
      const submitData = { ...formData.value }
      if (submitData.rewardType !== 1) {
        submitData.redPacketAmount = 0
      }
      if (submitData.rewardType !== 2) {
        submitData.giftActivityIds = []
      }
      NewCustomerConfigApi.write(submitData)
    }
  })
}

const computedOriginPrice = computed({
  get: () => {
    return Number(fenToYuan(formData.value.originPrice))
  },
  set: (value) => {
    formData.value.originPrice = yuanToFen(value)
  }
})
const computedPrice = computed({
  get: () => {
    return Number(fenToYuan(formData.value.price))
  },
  set: (value) => {
    formData.value.price = yuanToFen(value)
  }
})
const computedRedPacketAmount = computed({
  get: () => {
    return Number(fenToYuan(formData.value.redPacketAmount))
  },
  set: (value) => {
    formData.value.redPacketAmount = yuanToFen(value)
  }
})

const loadConfig = async () => {
  formLoading.value = true
  try {
    formData.value = await NewCustomerConfigApi.read()
    // 如果是优惠券类型，加载优惠券模板列表
    if (formData.value.rewardType === 2) {
      await loadCouponTemplates()
    }
  } finally {
    formLoading.value = false
  }
}

const tableData = reactive({
  total: 0,
  loading: true,
  list: [],
  searchParam: {
    pageNo: 1,
    pageSize: 10,
    createTime: []
  }
})

const loadTableData = async () => {
  tableData.loading = true
  try {
    const res = await NewCustomerConfigApi.getPage({
      ...tableData.searchParam
    })
    tableData.list = res.list
    tableData.total = res.total
  } finally {
    tableData.loading = false
  }
}

onMounted(async () => {
  if (checkRole(['shop_admin'])) {
    await loadConfig()
    return
  }
  tableData.searchParam.pageNo = 1
  await loadTableData()
})
</script>
